//
//  WebLinkViewController.m
//  PersonalTool
//
//  Created by Samuel on 2/11/15.
//  Copyright (c) 2015 Samuel. All rights reserved.
//

#import "WebLinkViewController.h"
#import "HTTPServer.h"
#import "MyHTTPConnection.h"
#import "localhostAdresses.h"

#define HTTP_SERVER_PORT (8080)

@interface WebLinkViewController ()
{
    HTTPServer      *webServer;
    NSDictionary    *ips;
    __weak IBOutlet UILabel *ipLabel;
}

@end

@implementation WebLinkViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionClosed:) name:HTTPConnectionDidDieNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindIps:) name:NOTIFICATION_RESOLVED_LOCALHOST_IP_ADDRS object:nil];
    typeof(self) __weak weakSelf = self;
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{
        dispatch_sync(concurrentQueue, ^{
            [weakSelf initHttpServer];
            [localhostAdresses list];
            
        });
        dispatch_sync(dispatch_get_main_queue(), ^{
            [weakSelf startHttpServer];
            
        }); });
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_RESOLVED_LOCALHOST_IP_ADDRS object:nil];
    [self stopHttpServer];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

//注意这里并不能直接改变progressView.progress的值 因为NSNotification也是运行在非主线程中的!
- (void)handleUploadProgressNotification:(NSNotification *) notification
{
    NSNumber *uploadProgress = (NSNumber *)[notification object];
    [self performSelectorOnMainThread:@selector(changeProgressViewValue:) withObject:uploadProgress waitUntilDone:NO];
}

- (void)changeProgressViewValue:(NSNumber *) value;
{
//    progressView.progress = [value floatValue];
//    [progressView setNeedsDisplay];
    NSLog(@"current progress value is %f", [value floatValue]);
}

#pragma mark - get ips
- (void)bindIps:(NSNotification *) notification
{
    ips = [(NSDictionary *)[notification object] copy];
    NSLog(@"IPs addresses: %@", ips);
}

- (void)displayIps
{
    NSString *en0Ip = nil;
//    NSString *wwwIp = nil;
    
    if (ips != nil)
    {
        if ([[ips allKeys] containsObject:@"en0"]) {
            en0Ip = (NSString *)[ips objectForKey:@"en0"];
//            en0IpLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 100, 260, 25)];
            ipLabel.text = [NSString stringWithFormat:@"局域网IP: %@:%d", en0Ip, HTTP_SERVER_PORT];
//            [self.view addSubview:en0IpLabel];
        }
        
        if ([[ips allKeys] containsObject:@"www"]) {
//            wwwIp = (NSString *)[ips objectForKey:@"www"];
//            wwwIpLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 130, 260, 25)];
//            wwwIpLabel.text = [NSString stringWithFormat:@"万维网IP: %@:%d", wwwIp, HTTP_SERVER_PORT];
//            [self.view addSubview:wwwIpLabel];
        }
    }
//    NSLog(@"\n en0Ip:%@ \n wwwIp:%@", en0Ip, wwwIp);
}

- (void)hideIps
{
//    if (en0IpLabel != nil) {
//        [en0IpLabel removeFromSuperview];
//        en0IpLabel = nil;
//    }
//    
//    if (wwwIpLabel != nil) {
//        [wwwIpLabel removeFromSuperview];
//        wwwIpLabel = nil;
//    }
}

#pragma mark - HTTPSERVER
- (void)initHttpServer
{
    if (webServer == nil) {
        webServer = [[HTTPServer alloc] init];
        webServer.port = HTTP_SERVER_PORT;
        webServer.documentRoot = [[NSBundle mainBundle] pathForResource:@"web" ofType:nil];
        webServer.type = @"_http._tcp.";
        webServer.connectionClass = [MyHTTPConnection class];
    }
}

- (void)startHttpServer
{
    if (webServer != nil && ![webServer isRunning]) {
//        progressView.progress = 0.0f;
        [self displayIps];
        [webServer start:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUploadProgressNotification:) name:UPLOAD_FILE_PROGRESS object:nil];
    }
}

- (void)stopHttpServer
{
    if (webServer != nil && [webServer isRunning]) {
        [self hideIps];
        [webServer stop];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UPLOAD_FILE_PROGRESS object:nil];
    }
}

- (void)connectionClosed:(NSNotification *) notification
{
//    if (progressView.progress < 1) {
//        NSLog(@"上传中止了!");
//    }
    
    NSLog(@"connectionClosed");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
